package com.heima.comment.interceptor;

import com.heima.model.common.user.pojo.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.AppThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 自定义的拦截器
 */
public class MvcHandleInterceptor implements HandlerInterceptor {
    //方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        Optional<String> optional = Optional.ofNullable(token);
        if(optional.isPresent()) {
            //2.解析token,获取用户id
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if(claimsBody!=null){
                Integer userId = (Integer) claimsBody.get("id");
                //3.存入threadLocal中
                ApUser wmUser = new ApUser();
                wmUser.setId(userId );
                AppThreadLocal.setApUser(wmUser);
            }
        }
        return true;
    }
    //方法之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //从threadLocal中清除用户信息
        AppThreadLocal.removeApUser();
    }
}